package com.yuexunit.operationman.nbsy.module.Login.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.yuexunit.operationman.nbsy.R;
import com.yuexunit.operationman.nbsy.Idata.ScannerInerface;

import com.yuexunit.operationman.nbsy.base.BaseKJActivity;
import com.yuexunit.operationman.nbsy.config.AppConfig;
import com.yuexunit.operationman.nbsy.module.Login.bean.PatientBean;
import com.yuexunit.operationman.nbsy.module.Login.model.impl.SearchModel;
import com.yuexunit.operationman.nbsy.module.Login.presenter.ISearchPresenter;
import com.yuexunit.operationman.nbsy.module.Login.presenter.impl.SearchPresenter;
import com.yuexunit.operationman.nbsy.module.Login.ui.view.ISearchView;
import com.yuexunit.operationman.nbsy.module.Patients.ui.Act_PatientDetail;
import com.yuexunit.operationman.nbsy.module.Patients.ui.Act_PatientList;
import com.yuexunit.operationman.nbsy.widget.LoadingDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2017/7/12.
 */
public class Act_Search extends BaseKJActivity implements ISearchView{
    @Bind(R.id.chemicalsearch_edt)
    EditText chemicalsearchEdt;

    LoadingDialog loadingDialog;
    ISearchPresenter presenter;

    ScannerInerface scanner;
    IntentFilter intentFilter;
    BroadcastReceiver scanReceiver;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_search);
        ButterKnife.bind(this);
    }

    @Override

    public void initData() {
        super.initData();
        loadingDialog = new LoadingDialog(this);
        presenter = new SearchPresenter(this,new SearchModel());
//        chemicalsearchEdt.setText("201722215");
    }

    @Override
    public void onResume(){
        super.onResume();
        initScanner();
    }

    @Override
    public void onStop(){
        super.onStop();
        finishScanner();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        finishScanner();
    }

    private void initScanner(){
        scanner = new ScannerInerface(this);
        scanner.open();	//打开扫描头上电   scanner.close();//打开扫描头下电
        scanner.enablePlayBeep(true);//是否允许蜂鸣反馈
        scanner.enableFailurePlayBeep(true);//扫描失败蜂鸣反馈
        scanner.enablePlayVibrate(true);//是否允许震动反馈
        scanner.setCharSetMode(4);//设置解码方式
        //		scanner.enablShowAPPIcon(false);//是否允许显示iscan的应用程序图标   部分设备 调用出现异常，建议不要调用该功能
        //		scanner.enablShowNoticeIcon(false);//是否允许显示iscan通知栏图标     部分设备 调用出现异常，建议不要调用该功能
        scanner.enableAddKeyValue(1);/**附加无、回车、Teble、换行*/
        scanner.timeOutSet(2);//设置扫描延时2秒
        scanner.intervalSet(10); //设置连续扫描间隔时间
        scanner.lightSet(false);//关闭右上角扫描指示灯
        scanner.enablePower(true);//省电模式
        //		scanner.addPrefix("AAA");//添加前缀
        //		scanner.addSuffix("BBB");//添加后缀
        //		scanner.interceptTrimleft(2); //截取条码左边字符
        //		scanner.interceptTrimright(3);//截取条码右边字符
        //		scanner.filterCharacter("R");//过滤特定字符
        //		scanner.SetErrorBroadCast(true);//扫描错误换行
        //      scanner.resultScan();//恢复iScan默认设置

        scanner.lockScanKey();
        //锁定设备的扫描按键,通过iScan定义扫描键扫描，用户也可以自定义按键。
//		scanner.unlockScanKey();
        //释放扫描按键的锁定，释放后iScan无法控制扫描按键，用户可自定义按键扫描。

        /**设置扫描结果的输出模式，参数为0和1：
         * 0为模拟输出（在光标停留的地方输出扫描结果）；
         * 1为广播输出（由应用程序编写广播接收者来获得扫描结果，并在指定的控件上显示扫描结果）
         * 这里采用接收扫描结果广播并在TextView中显示*/
        scanner.setOutputMode(1);

        //扫描结果的意图过滤器的动作一定要使用"android.intent.action.SCANRESULT"
        intentFilter = new IntentFilter(AppConfig.IDATA);
        //注册广播接受者
        scanReceiver = new ScannerResultReceiver();
        registerReceiver(scanReceiver, intentFilter);
    }

    /**
     * 结束扫描
     */
    private void finishScanner(){
        scanner.scan_stop();
        //    	 scanner.close();	//关闭iscan  非正常关闭会造成iScan异常退出
        try {
            unregisterReceiver(scanReceiver);	//反注册广播接收者
        } catch (IllegalArgumentException e) {

        }
        scanner.continceScan(false);
    }

    @OnClick({R.id.img_back, R.id.chemicalsearch_btn, R.id.nurse})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.chemicalsearch_btn:
                presenter.getPatientDate(chemicalsearchEdt.getText().toString());
                break;
            case R.id.nurse:
                startActivity(new Intent(aty, Act_PatientList.class));
                break;
        }
    }

    @Override
    public void getPatientDate(PatientBean patientBean) {
        if(patientBean.getCode() == 200)
        {
            if(patientBean.getObject().size() == 1)
            {
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_NAME, patientBean.getObject().get(0).getPatientName());
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_AGE, patientBean.getObject().get(0).getPatientAge()+"");
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_SEX, patientBean.getObject().get(0).getPatientSex());
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DATE, patientBean.getObject().get(0).getHospitalDateStr());
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DOCTOR, patientBean.getObject().get(0).getOperator());
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_BED, patientBean.getObject().get(0).getPatientBed());
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DIAGNOSIS, patientBean.getObject().get(0).getPreOperation());
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_VISITNO, patientBean.getObject().get(0).getInHospitalNo());
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_OPERATION_ID, patientBean.getObject().get(0).getOperationNo()+"");
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DISEASE, patientBean.getObject().get(0).getOperandi());
                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_ORDER_TIME, patientBean.getObject().get(0).getOperationOrderDateStr());
                AppConfig.initDate();
//                if(patientBean.getObject().get(0).getDepartment().contains("眼"))
//                {
//                    AppConfig.isEye = true;
//                }
//                else {
//                    AppConfig.isEye = false;
//                }
                startActivity(new Intent(aty, Act_PatientDetail.class));
            }
            else {
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_NAME, patientBean.getObject().get(0).getPatientName());
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_AGE, patientBean.getObject().get(0).getPatientAge());
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_SEX, patientBean.getObject().get(0).getPatientSex());
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DATE, patientBean.getObject().get(0).getHospitalDateStr());
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DOCTOR, patientBean.getObject().get(0).getOperator());
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_BED, patientBean.getObject().get(0).getPatientBed());
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DIAGNOSIS, patientBean.getObject().get(0).getPreOperation());
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_VISITNO, patientBean.getObject().get(0).getInHospitalNo());
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_OPERATION_ID, patientBean.getObject().get(0).getOperationNo()+"");
//                PreferenceHelper.write(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DISEASE, patientBean.getObject().get(0).getOperandi());
//                startActivity(new Intent(aty, Act_PatientDetail.class));
                Intent intent = new Intent(aty,Act_SearchList.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("object",patientBean.getObject());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }
        else {
            ViewInject.toast(patientBean.getDesc());
        }
    }

    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                loadingDialog.dismiss();
                break;

        }
    }

    /**
     * 扫描结果的广播接收者
     */
    private class ScannerResultReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(AppConfig.IDATA)){
                //获取扫描结果
                final String result = intent.getStringExtra("value");
                if(!result.equals(""))
                {
                    if(result.length() == 8)
                    {
                        chemicalsearchEdt.setText(result);
                        presenter.getPatientDate(result);
                    }
                }
                else {
                    ViewInject.toast("非住院号，请扫描住院号");
                }
            }
        }
    }

}
